import socket
import threading
import os
import time


def clear_screen():
    """清屏功能"""
    os.system('cls' if os.name == 'nt' else 'clear')


def receive_messages(client_socket):
    """接收来自服务器的消息"""
    try:
        while True:
            data = client_socket.recv(1024).decode('utf-8')
            if not data:
                print("\n服务器已断开连接")
                break
            print(f"\r\n服务端说: {data}")
            print("客户端说: ", end='', flush=True)  # 重新显示输入提示
    except Exception as e:
        print(f"\n接收消息时出错: {e}")
    finally:
        client_socket.close()


def start_client():
    # 创建客户端套接字
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 连接服务器
    host = 'localhost'
    port = 12345

    try:
        client_socket.connect((host, port))
        clear_screen()
        print(f"已连接到服务器 {host}:{port}")
        print("输入 'exit' 退出聊天")
        print("=" * 50)

        # 创建接收消息的线程
        receive_thread = threading.Thread(
            target=receive_messages,
            args=(client_socket,)
        )
        receive_thread.daemon = True
        receive_thread.start()

        # 主线程负责发送消息
        while True:
            message = input("客户端说: ")
            if message.lower() == 'exit':
                break
            elif message.lower() == 'clear':
                clear_screen()
                print("聊天已清屏")
                continue
            client_socket.send(message.encode('utf-8'))

    except Exception as e:
        print(f"连接或发送消息时出错: {e}")
    finally:
        client_socket.close()
        print("已断开与服务器的连接")


if __name__ == "__main__":
    start_client()